﻿using Microsoft.EntityFrameworkCore;


namespace EntityModels
{
    /// <summary>
    /// 数据种子
    /// </summary>
    public class DataSeedingContext : DbContext
    {
        public DbSet<DataSeedingEntity> DataSeedingEntities => Set<DataSeedingEntity>();

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<DataSeedingEntity>()
                // 使用实体类对象提供数据
                .HasData(new DataSeedingEntity { Id = 1, Text = "Text" });
            // 使用匿名对象提供数据
            modelBuilder.Entity<DataSeedingEntity>().HasData(new { Id = 2, Text = "Text" });


        }

    }

    public class DataSeedingEntity
    {
        public int Id { get; set; }
        public string Text { get; set; }
    }

    public class UseDataSeeding
    {
        void MyMethod()
        {
            using (var context = new DataSeedingContext())
            {
                context.Database.EnsureCreated();
                var entity = context.DataSeedingEntities.FirstOrDefault(b => b.Text == "Text");
                if (entity == null)
                {
                    context.DataSeedingEntities.Add(new DataSeedingEntity { Text = "Text" });
                }
                context.SaveChanges();

            }

        }

    }


}
